#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include "ncu_param.h"
#ifdef DMALLOC
#include <imp/dmalloc.h>
#endif
typedef struct {
	ncu_params nparams;
}ncumsg;

int main(int argc, char **argv)
{

	int ret = 0;
	int  socketfd;
	struct sockaddr_in svraddr;
	struct sockaddr_in localaddr;


	if (6 != argc) {
		printf("err: param error\n");
		printf("usage: cmd ncu_jxf22.bin clientip clientport serverip serverport\n");
		return -1;
	}

	printf("config file: %s\n", argv[1]);
	printf("client ip: %s\n", argv[2]);
	printf("client port: %s\n", argv[3]);
	printf("server ip: %s\n", argv[4]);
	printf("server port: %s\n", argv[5]);

	socketfd = socket (AF_INET, SOCK_DGRAM, 0);
	if ( -1 == socketfd )
	{
		printf("error: socket create err %s\n", strerror(errno));
		exit(-1);
	}

	int option = 1;
	setsockopt( socketfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option) );
	memset(&localaddr, 0, sizeof(localaddr));
	localaddr.sin_family = AF_INET;
	localaddr.sin_addr.s_addr = inet_addr( argv[2]);
	localaddr.sin_port = htons (atoi(argv[3]));

	int bindResult = bind(socketfd, (struct sockaddr *) &localaddr, sizeof(localaddr));
	if ( -1 == bindResult )
	{
		printf("error: socket bind err %s\n", strerror(errno));
		close(socketfd);
		exit(-1);
	}

	memset(&svraddr, 0, sizeof(svraddr));
	svraddr.sin_family = AF_INET;
	svraddr.sin_addr.s_addr = inet_addr( argv[4]);
	svraddr.sin_port = htons (atoi(argv[5]));


	ncumsg msg;
	memset(&msg, 0, sizeof(msg));


	FILE *fp = NULL;
	fp = fopen(argv[1], "r");
	if (NULL == fp) {
		printf("err: fopen fp err\n");
		return -1;
	}

	ret = fread(&msg.nparams, sizeof(ncu_params), 1, fp);
	if (1 != ret) {
		printf("error: ncu bin file read %s\n", strerror(errno));
		exit(-1);
	}

	ssize_t retsize = sendto(socketfd, &msg, sizeof(msg), 0, (struct sockaddr*)&svraddr, sizeof(svraddr));
	if (-1 == retsize) {
		printf("error: socket send err %s\n", strerror(errno));
	} else {
		printf("info: send data success, len:%ld\n", retsize);
	}
	close(socketfd);
}

